import { useEffect } from "react";
import {
  CameraSetting,
  ExtensionCategory,
  Graph,
  register,
  type GraphOptions,
  
} from "@antv/g6";
import {
  Light,
  Line3D,
  ObserveCanvas3D,
  Sphere,
  ZoomCanvas3D,
  renderer,
} from "@antv/g6-extension-3d";

// 注册3D扩展组件
register(ExtensionCategory.PLUGIN, "3d-light", Light);
register(ExtensionCategory.NODE, "sphere", Sphere);
register(ExtensionCategory.EDGE, "line3d", Line3D);
register(ExtensionCategory.PLUGIN, "camera-setting", CameraSetting);
register(ExtensionCategory.BEHAVIOR, "zoom-canvas-3d", ZoomCanvas3D);
register(ExtensionCategory.BEHAVIOR, "observe-canvas-3d", ObserveCanvas3D);

// 定义数据类型接口
interface GraphNode  {
  data: {
    degree: number;
    x: number;
    y: number;
    z: number;
    cluster: string;
  };
}

interface GraphEdge {
  source: string;
  target: string;
}

interface GraphData {
  nodes: GraphNode[];
  edges: GraphEdge[];
}

export default function RotatingSolar() {
  useEffect(() => {
    let graph: Graph;
    let animationFrameId: number;

    // 获取并处理数据
    fetch("https://assets.antv.antgroup.com/g6/eva-3d-data.json")
      .then((res) => res.json())
      .then((rawData: unknown) => {
        const { nodes, edges } = rawData as GraphData;
        const degreeMap = new Map<string, number>();

        // 计算节点度数
        edges.forEach(({ source, target }) => {
          degreeMap.set(source, (degreeMap.get(source) || 0) + 1);
          degreeMap.set(target, (degreeMap.get(target) || 0) + 1);
        });

        // 增强节点数据
        const enhancedNodes = nodes.map((node:any) => ({
          ...node,
          data: {
            ...node.data,
            degree: degreeMap.get(node.id) || 0,
          },
        }));

        return { nodes: enhancedNodes, edges };
      })
      .then((data: any) => {
        // 图表配置
        const graphOptions: GraphOptions = {
          container: "sbyyyyyyy",
          renderer,
          width: 300,
          height: 200,
          data,
          animation: false,
          background:"#ff7300", //背景色
          node: {
            type: "sphere",
            style: {
              materialType: "phong",
              size: (d: any) => 50 + d.data.degree,
              x: (d: any) => d.data.x,
              y: (d: any) => d.data.y,
              z: (d: any) => d.data.z,
            },
            palette: {
              color: "tableau",
              type: "group",
              field: "cluster",
            } as const, // 明确类型断言
          },
          edge: {
            type: "line3d",
            style: {
              lineWidth: 0.4,
              opacity: 0.4,
              stroke: "#fff",
            },
          },
          behaviors: ["observe-canvas-3d", "zoom-canvas-3d"],
          plugins: [
            // 水印
            {
              type: 'watermark',
              text: 'G6: Graph Visualization',
              textFontSize: 14,
              textFontFamily: 'Microsoft YaHei',
              fill: 'rgba(0, 0, 0, 0.1)',
              rotate: Math.PI / 12,
            },
            {
              type: "camera-setting",
              projectionMode: "orthographic",
              near: 1,
              far: 10000,
              fov: 45,
              aspect: 1,
            },
            {
              type: "3d-light",
              directional: {
                direction: [0, 0, 1] as [number, number, number],
              },
            },
            {
              type: "background",
              width:"350px",
              height:"200",
              backgroundImage: 'url(https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*0Qq0ToQm1rEAAAAAAAAAAAAADmJ7AQ/original)',
      backgroundRepeat: 'no-repeat',
      backgroundSize: 'cover',
      opacity: 0.2,
            },
          ],
        };

        graph = new Graph(graphOptions);

        // 绘制图表
        return graph.draw();
      })
      .then(() => {
        // 运行动画
        const camera:any = graph.getCanvas().getCamera();
        let counter = 0;

        const animate = () => {
          if (counter < 80) {
            camera.dolly(4);
          }
          camera.rotate(0.4, 0);
          counter++;

          if (counter <= 160) {
            animationFrameId = requestAnimationFrame(animate);
          }
        };

        animationFrameId = requestAnimationFrame(animate);
      })
      .catch((error) => {
        console.error("Graph initialization failed:", error);
      });

    // 清理函数
    return () => {
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
      if (graph) {
        graph.destroy();
      }
    };
  }, []);

  return (
    <div
      id="sbyyyyyyy"
      style={{
        border: "1px solid #e8e8e8",
        width: "300px",
        height: "200px",
      }}
    />
  );
}